package revontuli.aMHD.UIhelpers;

import java.util.ArrayList;
import java.util.ListIterator;

import revontuli.aMHD.dataclasses.Stop;
import revontuli.aMHD.R;
import revontuli.aMHD.LineScheduleAct;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class LineScheduleRouteAdapter extends BaseAdapter implements OnClickListener{
	private ArrayList<Stop> mList = new ArrayList<Stop>();
	private Context mContext;

	public LineScheduleRouteAdapter(Context context, ArrayList<Stop> list) {
		this.mContext = context;
		this.mList = list;
	}

	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public Object getItem(int pos) {
		return mList.get(pos);
	}

	@Override
	public long getItemId(int pos) {
		return pos;
	}

	@Override
	public View getView(int pos, View mView, ViewGroup mViewGroup) {
		Stop mStop = mList.get(pos);
		
		if (mView == null) {
			LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mView = mInflater.inflate(R.layout.lineschedulerouteitem, null);
		}
		
		RelativeLayout riadok = (RelativeLayout) mView.findViewById(R.id.LineScheduleRouteItem);
		riadok.setOnClickListener(this);
		riadok.setTag(pos);
		
		TextView mName = (TextView) mView.findViewById(R.id.lineScheduleStopName);
		mName.setText(mStop.name);
		
		TextView mDistance = (TextView) mView.findViewById(R.id.lineScheduleStopDistance);
		ListIterator<Stop> it = mList.listIterator();
		if (pos>((LineScheduleAct)mContext).actualStop) {
			int suma = 0;
			for (int i=((LineScheduleAct)mContext).actualStop+1; i<=pos; i++) {
				suma += mList.get(i).distance;
			}
			
			mDistance.setText(Integer.toString(suma));
		} else if (pos == ((LineScheduleAct)mContext).actualStop) {
			mDistance.setText("0");
		} else {
			mDistance.setText("");
		}
		return mView;
	}

	@Override
	public void onClick(View v) {
		((LineScheduleAct)mContext).actualStop = (Integer)v.getTag();
		((LineScheduleAct)mContext).mRouteAdapter.notifyDataSetChanged();
		
	}

}
